﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.IO;

namespace dotNetInteropPlugin.CSharpMixingLibrary
{
    internal static class CustomAssemblyResolver
    {
        private static string CurPath = null;
        private static bool IsInited = false;
        public static void Initialize(string Path)
        {
            CurPath = Path;
            if (!IsInited)
            {
                AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
                IsInited = true;
            }
        }

        //public static void SubscribeToExternalDomain(AppDomain dmn)
        //{  
        //    dmn.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
        //}
        //public static void UnsubscribeFromExternalDomain(AppDomain dmn)
        //{
        //    dmn.AssemblyResolve -= new ResolveEventHandler(CurrentDomain_AssemblyResolve);
        //}

        static System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
        {
            string projectDir = Path.GetDirectoryName(CurPath);
            string shortAssemblyName = args.Name.Substring(0, args.Name.IndexOf(','));
            string fileName = Path.Combine(projectDir, shortAssemblyName + ".dll");
            if (File.Exists(fileName))
            {
                Assembly result = Assembly.LoadFrom(fileName);
                return result;
            }
            else
                return Assembly.GetExecutingAssembly().FullName == args.Name ? Assembly.GetExecutingAssembly() : null;
        }


        public static void Deinitialize()
        {
            AppDomain.CurrentDomain.AssemblyResolve -= new ResolveEventHandler(CurrentDomain_AssemblyResolve);
            IsInited = false;
        }
    }
}
